//
//  Messagelist.m
//  YunBo
//
//  Created by huoyan on 8/2/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Messagelist.h"
#import "ForWardingView.h"
#import "Status.h"
#import "User.h"
#import "ManagerAdapter.h"
#import "BaseStatus.h"
#import "ManagerAdapter.h"

#define CELL_CONTENT_WITH               260.0f
#define CELL_CONTENT_MARGIN             10.0f    
#define FONT_SIZE                       15.0f






@implementation Messagelist

@synthesize contenTextHeight;
@synthesize tableViewC;
@synthesize type;
@synthesize statuses;

//count the label height

-(void)viewDidLoad
{
    self = [super init];
}


//
//- (void)viewDidAppear:(BOOL)animated
//{   
//    NSLog(@"dsf");
//    id manager = [[ManagerAdapter instance] getManager:2];
//    self.statuses = [manager getHomeMsgWithResultType:RESULTTYPE_JSON
//                                            pageFlage:PAGEFLAG_FIRST
//                                              nReqNum:100];
//}


//- (void) update
//{
//        NSLog(@"dsf");
//        id manager = [[ManagerAdapter instance] getManager:2];
//        self.statuses = [manager getHomeMsgWithResultType:RESULTTYPE_JSON
//                                                pageFlage:PAGEFLAG_FIRST
//                                                  nReqNum:100];
//}





-(CGFloat)countHeight:(NSString *)s textSize:(CGFloat)textSize frameWidth:(CGFloat) width
{
    
    
 
    CGSize constraint= CGSizeMake(width, 2000.0f);
    CGSize size =[s sizeWithFont:[UIFont systemFontOfSize:textSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeCharacterWrap];
    CGFloat height = MAX(size.height, 30.0f);
    
    return height;
    
    
}

//draw a ForWarding frame using a status

-(void) drawForWarding:(ForWardingView *)forWarding usingStatus:(Status *)status
{

    UILabel *contentTex;
    UIImageView *sendthumbmailPic;
    CGRect rectContenTex =CGRectMake(10, 15, 235, 0);
    CGRect rectThumbmail;
    NSInteger labelHeight;
   
    contentTex = [[UILabel alloc] initWithFrame:rectContenTex];
    [contentTex setLineBreakMode:UILineBreakModeCharacterWrap];
 //   [contentTex setLineBreakMode:UILineBreakModeWordWrap];
    
 //   [contentTex setTextAlignment:UITextAlignmentCenter];
    [contentTex setFont:[UIFont systemFontOfSize:11]];
    [contentTex setNumberOfLines:0];
    [contentTex setTag:3];
   
    [contentTex setBackgroundColor:[UIColor colorWithRed:191.0/255.0 green:293.0/255.0 blue:255.0/255.0 alpha:0]];
    [contentTex setText:[[status.user.name stringByAppendingString:@" : "] stringByAppendingString:status.text] ];
    labelHeight=[self countHeight:status.text textSize:11 frameWidth:235];
    [contentTex setFrame:CGRectMake(10 ,15,235,labelHeight)];
    
    if ([status.thumbnail_pic length]!=0) {
        
        rectThumbmail =CGRectMake(10, labelHeight+25, 70, 50);
        sendthumbmailPic= [[UIImageView alloc] initWithFrame:rectThumbmail];
        NSData *data2=[NSData dataWithContentsOfURL:[NSURL URLWithString:status.thumbnail_pic]];
        UIImage *img2=[UIImage imageWithData:data2];
        [sendthumbmailPic setImage:img2];
        [sendthumbmailPic setTag:4];
        
    } 
    
    [forWarding addSubview:contentTex];
    if ([status.thumbnail_pic length] !=0) {
        [forWarding addSubview:sendthumbmailPic];
    }
    
    [contentTex release];
    
    if ([status.thumbnail_pic length]!=0) {
     [sendthumbmailPic release];
    }
}


//draw a cell

   
-(UITableViewCell *)drawPPic:(NSString *)plofileImage drawUser:(NSString *)user drawTime:(NSString *) createdAt
                    drawText:(NSString *)text drawPic:(NSString *) thumbmailPic drwaStatus:(Status *)retweetedStatus drawFromSouce:(NSString *)source;
{
    
     UIImageView *userPic;
     UILabel *userName;
     UILabel *creatTime;
     UILabel *contentTex;
     UILabel *fromSouce;
    UIImageView *sendthumbmailPic;
    ForWardingView *retweeted;
    
    

    
     CGRect rectUserPic =CGRectMake(10, 10, 50, 50);
     CGRect rectUserName =CGRectMake(65, 4, 125, 30);
     CGRect rectCreatTime =CGRectMake(205, 4, 110, 30);
     CGRect rectContenTex =CGRectMake(65, 44, 250, 0);
     CGRect rectFromSouce;
    CGRect rectThumbmail;
    NSInteger labelHeight;
    
    userPic =[[UIImageView alloc] initWithFrame:rectUserPic];
    [userPic setTag:0];
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:plofileImage]];
	UIImage *img=[UIImage imageWithData:data];
	[userPic setImage:img];
    
    
    
    userName =[[UILabel alloc] initWithFrame:rectUserName];
    [userName setFont:[UIFont systemFontOfSize:12]];
    [userName setTag:1];
    [userName setText:user];
 
  
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
   
    
   // NSDate *date =[dateFormatter dateFromString:createdAt];
   // NSString  *formattedDateString = [dateFormatter stringFromDate:date];
    NSString *formattedDateString = createdAt;

    

    creatTime = [[UILabel alloc] initWithFrame:rectCreatTime];
    [creatTime setFont:[UIFont systemFontOfSize:12]];
    [creatTime setTag:2];
    [creatTime setText:formattedDateString];
    
  
    
    contentTex = [[UILabel alloc] initWithFrame:rectContenTex];
    [contentTex setLineBreakMode:UILineBreakModeCharacterWrap];
    [contentTex setFont:[UIFont systemFontOfSize:FONT_SIZE]];
    [contentTex setNumberOfLines:0];
    [contentTex setTag:3];
    [contentTex setText:text];
    labelHeight=[self countHeight:contentTex.text textSize:FONT_SIZE frameWidth:CELL_CONTENT_WITH];
    [contentTex setFrame:CGRectMake(65,44,CELL_CONTENT_WITH,labelHeight)];
    
    
    if (retweetedStatus!=nil && [retweetedStatus.thumbnail_pic length]==0) {
        
        forWardingHeight=[self countHeight:retweetedStatus.text textSize:11 frameWidth:235]+25;
    }
    
    
    if (retweetedStatus != nil && [retweetedStatus.thumbnail_pic length ]!=0) {
        
        forWardingHeight=[self countHeight:retweetedStatus.text textSize:11 frameWidth:235]+85;
    }
    
    
    
    
    
    
    if ([thumbmailPic length]!=0) {

    rectThumbmail =CGRectMake(65, labelHeight+54, 80, 60);
    sendthumbmailPic= [[UIImageView alloc] initWithFrame:rectThumbmail];
    NSData *data2=[NSData dataWithContentsOfURL:[NSURL URLWithString:thumbmailPic]];
	UIImage *img2=[UIImage imageWithData:data2];
	[sendthumbmailPic setImage:img2];
    [sendthumbmailPic setTag:4];
    
    } 
    
    if([thumbmailPic length]!=0)
    {
        
        if (retweetedStatus != nil) {
            CGRect rectRetWeeted =CGRectMake(65, labelHeight+54+60+10, 245, forWardingHeight);
            
            retweeted = [[ForWardingView alloc] initWithFrame:rectRetWeeted];
            
            UIColor *color =[UIColor colorWithWhite:2 alpha:0];
            
            
            
            [retweeted setBackgroundColor:color];
            
            [self drawForWarding:retweeted usingStatus:retweetedStatus];
         
        }
        
    }   
   else
   {
       if(retweetedStatus != nil)
       {
           CGRect rectRetWeeted =CGRectMake(65, labelHeight+54,245, forWardingHeight);
           retweeted = [[ForWardingView alloc] initWithFrame:rectRetWeeted];
           UIColor *color =[UIColor colorWithWhite:0 alpha:0];
           [retweeted setBackgroundColor:color ];
           
        
           [self drawForWarding:retweeted usingStatus:retweetedStatus];
           
          
           
          
           
       }
   }
  
    
    if (retweetedStatus != nil && [thumbmailPic length] !=0)
    {
        rectFromSouce = CGRectMake(60, labelHeight+54+60+10+forWardingHeight+10, 100, 10);
    }
    else if(retweetedStatus != nil && [thumbmailPic length] ==0)
    {
        rectFromSouce = CGRectMake(60, labelHeight+54+forWardingHeight+10, 100, 10);
    }
    else if(retweetedStatus == nil && [thumbmailPic length] !=0)
    {
        rectFromSouce =CGRectMake(60, labelHeight+54+60+10, 100, 10);
        
    }
    else
    {
        rectFromSouce = CGRectMake(60, labelHeight+54, 100, 10);
    }
    
    fromSouce =[[UILabel alloc] initWithFrame:rectFromSouce];
    [fromSouce setTag:5];
    [fromSouce setFont:[UIFont systemFontOfSize:10]];
    NSString *comeFrom = [NSString stringWithString:@"来自"]; 
    [fromSouce setText:[comeFrom stringByAppendingString:source]];
    UITableViewCell *cell =[[[UITableViewCell alloc] initWithFrame:CGRectZero] autorelease];
    
    [[cell contentView] addSubview:userPic];
    [[cell  contentView] addSubview:userName];
    [[cell contentView] addSubview:creatTime];
    [[cell contentView] addSubview:contentTex];
    if ([thumbmailPic length]!=0) {
        [[cell contentView] addSubview:sendthumbmailPic];
        
    }
    if(retweetedStatus !=nil)
    {
        [[cell contentView] addSubview:retweeted];
    }
  [[cell contentView] addSubview:fromSouce];
    
    
    [userPic release];
    [userName release];
    [creatTime release];
    [contentTex release];
    [fromSouce release];
    if([thumbmailPic length]!=0){   
    
        [sendthumbmailPic release];
    }

    return cell;
}







#pragma mark -
#pragma mark Memory management



- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    
}
- (void)dealloc {
	[tableViewC release];
    [super dealloc];
}
#pragma mark -
#pragma mark Table Data Source Methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height;
    NSString *text;
    Status *stsa = [statuses objectAtIndex:indexPath.row];
    text =stsa.text;
    height = [self countHeight:text textSize:FONT_SIZE frameWidth:CELL_CONTENT_WITH];
    
    
    if (stsa.retweeted_status!=nil && [stsa.retweeted_status.thumbnail_pic length]==0) {
        
        forWardingHeight=[self countHeight:stsa.retweeted_status.text textSize:11 frameWidth:235]+45;
    }
    
        
    if (stsa.retweeted_status != nil && [stsa.retweeted_status.thumbnail_pic length ]!=0) {
            
            forWardingHeight=[self countHeight:stsa.retweeted_status.text textSize:11 frameWidth:235]+95;
        }
        
    
    if ([stsa.thumbnail_pic length]!=0 && stsa.retweeted_status != nil) {
        
        return height+44+10+60+forWardingHeight+10+20;
        
        
    }
    
    if([stsa.thumbnail_pic length]!=0 && stsa.retweeted_status == nil)
    {
        return height+44+10+60+10+20;
    }
    
    if([stsa.thumbnail_pic length]==0 && stsa.retweeted_status != nil)
    {
        return height+44+10+forWardingHeight+20;
    }
   
    
    return height+44+10+20;
    
}



- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{
	return statuses.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    NSString *text;
    NSString *userName;
    NSString *userPic;
    NSString *fromSource;
    NSString   *time;
    NSString *thumPic;
    Status *stsIner;
    Status *sts = [statuses objectAtIndex:indexPath.row];
    userName = sts.user.screen_name;
    text = sts.text;
  
//    NSArray *source =[sts.source componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
//    fromSource = [source objectAtIndex:2];
    fromSource =sts.source;
    time = sts.created_at;
    
    thumPic =sts.thumbnail_pic;
    userPic = sts.user.profile_image_url;
    stsIner = sts.retweeted_status;
    static NSString *MessageCellIdentifier = @"MessageCellIdentifier";
    UITableViewCell *cell =(UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:MessageCellIdentifier];
    if(cell == nil)
    {
        cell = [self drawPPic:userPic drawUser:userName drawTime:time drawText:text drawPic:thumPic drwaStatus:stsIner drawFromSouce:fromSource];
    }
    return cell;
}

@end
